package wd

import (
	"fmt"
	"time"

	_ "github.com/lestrrat-go/file-rotatelogs"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	logger "github.com/sirupsen/logrus"
)

type logHook struct {
}

func (hook logHook) Levels() []logger.Level {
	return logger.AllLevels
}

func (hook logHook) Fire(entry *logger.Entry) error {
	if entry.Context != nil {
		entry.Data["trace_id"] = entry.Context.Value("trace_id")
	}
	return nil
}

// initLogs 初始化日志
func initLogs() {
	App.SysLog = creatLog(1)
	App.Logger = creatLog(2)
	fmt.Printf("初始化日志成功:%s\n", time.Now().Format("2006-01-02 15:04:05"))
}

// creatLog 创建日志
func creatLog(logType int) *logger.Logger {
	log := logger.New()
	log.SetFormatter(&logger.JSONFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	})
	log.SetLevel(logger.InfoLevel)
	log.AddHook(logHook{})
	basePath := "./logs"
	if logType == 1 {
		basePath += "/sys_"
	} else {
		basePath += "/biz_"
	}
	basePath += "%Y%m%d%H.log"
	writer, err := rotatelogs.New(basePath,
		rotatelogs.WithMaxAge(24*7*time.Hour),
		rotatelogs.WithRotationTime(time.Minute),
	)
	if err != nil {
		panic(fmt.Sprintf("初始化日志失败:%+v", err))
	}
	log.SetOutput(writer)
	return log
}

// LogClose 关闭资源
func LogClose() {
	fmt.Println("关闭日志资源")
	App.SysLog.Exit(1)
	App.Logger.Exit(1)
}
